package cn.zhou.basic.service.impl;

import cn.zhou.basic.BaseConstant;
import cn.zhou.basic.dto.LoginDto;
import cn.zhou.basic.dto.WechatDto;
import cn.zhou.basic.exception.BusinessException;
import cn.zhou.basic.jwt.JwtUtils;
import cn.zhou.basic.jwt.LoginResult;
import cn.zhou.basic.jwt.RsaUtils;
import cn.zhou.basic.service.ILoginService;
import cn.zhou.basic.util.AjaxResult;
import cn.zhou.basic.util.HttpClientUtils;
import cn.zhou.basic.util.MD5Utils;
import cn.zhou.basic.util.StrUtils;
import cn.zhou.system.domain.Menu;
import cn.zhou.system.mapper.MenuMapper;
import cn.zhou.system.mapper.PermissionMapper;
import cn.zhou.user.domain.Logininfo;
import cn.zhou.user.domain.User;
import cn.zhou.user.domain.Wxuser;
import cn.zhou.user.mapper.LogininfoMapper;
import cn.zhou.user.mapper.UserMapper;
import cn.zhou.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
//    @Autowired
//    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public Map<String, Object> login(LoginDto dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        Integer type = dto.getType();
        //1.非空判断
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(type)) {
            throw new BusinessException("参数不能为空");
        }

        //2. 需要根据user和tpype n拿到数据库的值，然后进行比较
        Logininfo logininfo = logininfoMapper.loadByUserOrType(username, type);

        if (logininfo == null) {
            throw new BusinessException("没得这个东西11 ，gun");
        }
        //存在的话判断密码是否正确
        String salt = logininfo.getSalt();
        String md5 = MD5Utils.encrypByMd5(password + salt);
        if (!md5.equals(logininfo.getPassword())) {
            throw new BusinessException("账号密码错误");
        }
        return loginSuccessHandler(logininfo);
//        //获取taken
//        String taken = UUID.randomUUID().toString();
//        // 存到redis
//        redisTemplate.opsForValue().set(
//                taken,
//                logininfo,
//                10,
//                TimeUnit.MINUTES
//        );
//        //返回taken 和loginfo
//        Map<String, Object> map = new HashMap<>();
//        map.put("token",taken);
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//        map.put("logininfo",logininfo);
//        return map;
        // 在登录成功之后判断登录人是否是员工 还是用户


    }

    private Map<String, Object> loginSuccessHandler(Logininfo logininfo) {
        // 使用封装号的一个类来进行判断
        LoginResult loginResult = new LoginResult();
        //把用户传进来的info    传入
        loginResult.setLogininfo(logininfo);
        //如果拿到的是员工，那么就给他赋予 按钮 和 权限
        if (logininfo.getType() == 0) {
            List<Menu> menus = menuMapper.loadMenusByLogininfoId(logininfo.getId());
            //4.2 按钮权限
            List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
            loginResult.setMenus(menus);
            loginResult.setPermissions(permissions);
        }
        //把登录人信息 + 权限 加密封装成JWT串，返回给前端
        //获取私钥
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
        // 拼接jwt
        String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginResult, privateKey, 30);
        Map<String, Object> map = new HashMap<>();
        map.put("token", jwtStr);// 此时的token是jwt串
        //我们是高级技师，应该考虑到一些敏感信息不要返回给前端
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo", logininfo);
        map.put("menus", loginResult.getMenus());
        map.put("permissions", loginResult.getPermissions());
        return map;

    }
        @Override
        public AjaxResult wechat (WechatDto dto){
            // 判断空否(可以不做)
            String code = dto.getCode();
            // 获取code
            if (StringUtils.isEmpty(code)) {
                throw new BusinessException("没有拿到code呀,干瞪眼");
            }
            // 根据code 拿到tolen 和 id
            String tokenUrl = BaseConstant.WeChatConstants.TOKEN_URL
                    .replace("APPID", BaseConstant.WeChatConstants.APPID)
                    .replace("SECRET", BaseConstant.WeChatConstants.SECRET)
                    .replace("CODE", code);
            String tokenStr = HttpClientUtils.httpGet(tokenUrl);
            JSONObject tokenObj = JSONObject.parseObject(tokenStr);
            String accessToken = tokenObj.getString("access_token");
            String openId = tokenObj.getString("openid");
            //根据id 查询t_wxuser中是否存在
            Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
            if (wxuser != null && wxuser.getUserId() != null) {
                Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
                //获取taken
                String taken = UUID.randomUUID().toString();
//                // 存到redis
//                redisTemplate.opsForValue().set(
//                        taken,
//                        logininfo,
//                        10,
//                        TimeUnit.MINUTES
//                );
//                //返回taken 和loginfo
//                Map<Object, Object> map = new HashMap<>();
//                map.put("token", taken);
//                logininfo.setSalt(null);
//                logininfo.setPassword(null);
//                map.put("logininfo", logininfo);
//                return new AjaxResult().setResultObj(map);
                return new AjaxResult().setResultObj(loginSuccessHandler(logininfo));

            }
            String binderParams = "?accessToken=" + accessToken + "&openId=" + openId;
            return new AjaxResult().setSuccess(false).setResultObj(binderParams);
        }

        @Override
        public Map<String, Object> binder (WechatDto dto){
            //根据phone 查询是否在user表里面存在
            User user = userMapper.loadByphone(dto.getPhone());
            //如果存在 那么就找到longinfo表 根据user表的id
            Logininfo logininfo = null;
            if (user != null) {
                // 存在 ，查询出longinfo的数据放在这里
                logininfo = logininfoMapper.loadByUserId(user.getId());
            } else {
                //需要生成新的user和loginfo表
                user = dto2User(dto);
                logininfo = user2Logininfo(user);
                logininfoMapper.add(logininfo);
                user.setLogininfoId(logininfo.getId());
                userMapper.add(user);
            }
            // 根据token 和openid获取
            String tokenUrl = BaseConstant.WeChatConstants.WXUSER_URL
                    .replace("ACCESS_TOKEN", dto.getAccessToken())
                    .replace("OPENID", dto.getOpenId());
            String tokenStr = HttpClientUtils.httpGet(tokenUrl);
            //  wx 表的格式
            Wxuser wxuser = JSONObject.parseObject(tokenStr, Wxuser.class);

            // 把数据存进wx表
            wxuser.setUserId(user.getId());
            wxuserMapper.add(wxuser);

            // 直接登录
            String taken = UUID.randomUUID().toString();
            // 存到redis
//            redisTemplate.opsForValue().set(
//                    taken,
//                    logininfo,
//                    10,
//                    TimeUnit.MINUTES
//            );
//            //返回taken 和loginfo
//            Map<String, Object> map = new HashMap<>();
//            map.put("token", taken);
//            logininfo.setSalt(null);
//            logininfo.setPassword(null);
//            map.put("logininfo", logininfo);
//            return map;
            return loginSuccessHandler(logininfo);
        }

    /**
     *
     * 这个是把数据装进longininfo的方法
     * @param user
     * @return
     */
    private Logininfo user2Logininfo (User user){
            Logininfo logininfo = new Logininfo();
            BeanUtils.copyProperties(user, logininfo);
            logininfo.setType(1);//注意：一定要手动设置type 前端用户注册  1
            return logininfo;

        }

        private User dto2User (WechatDto dto){
            User user = new User();
            user.setUsername(dto.getPhone());
            user.setPhone(dto.getPhone());
            String salt = StrUtils.getComplexRandomString(32);
            String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
            user.setSalt(salt);
            user.setPassword(md5Pwd);
            return user;

        }

}
